package com.breaktian.assemble.socket.tcp;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import android.util.Log;

import com.breaktian.assemble.socket.callback.ListenTcpCallBack;


public class TcpSocketTwo {
	
	private Socket tcpSocket;
	
	private int timeout = 100000;//100秒

	private DataOutputStream dos;

	private DataInputStream dis;
	
	private TcpStateListener mTcpStateListener;

	public TcpSocketTwo(){
		tcpSocket = new Socket();
	}
	
	public TcpSocketTwo connect(String remoteIp, int remotePort){
		if(tcpSocket==null) {
			throw null;
		}
		try {
			SocketAddress remoteAddr = new InetSocketAddress(InetAddress.getByName(remoteIp), remotePort);
			tcpSocket.connect(remoteAddr,timeout);
			dis = new DataInputStream(tcpSocket.getInputStream());			
			new Thread(){
				public void run(){
					if(mTcpStateListener!=null){
						mTcpStateListener.onTCPConnected();  //回调上层连接状态
					}
				}
			}.start();
		} catch (IOException e) {
			e.printStackTrace();
			Log.d("TcpSocketTwo", "connect IOException##########################################1");
		}
		return this;
	}
	
	/**
	 * 发送数据 64kb以下
	 * 有返回数据
	 * */
	public void send(String s){
		if(tcpSocket==null){
			return;
		}
		try {
			dos = new DataOutputStream(tcpSocket.getOutputStream());
			System.out.println("cliendt发送数据："+s);
			dos.writeUTF(s);
			System.out.println("cliendt发送数据完毕");
			
		} catch (IOException e) {
			e.printStackTrace();
			Log.d("TcpSocketTwo", "writeUTF IOException##########################################2");
		}
	}
	
	
	
	public void listen(final ListenTcpCallBack call){
		new Thread(){
			public void run(){
				System.out.println("cliendt开始监听");
				if(dis==null){ 
					return;
				}
				try {
					while(true){
						System.out.println("cliendt读取数据，阻塞状态中");
						dis = new DataInputStream(tcpSocket.getInputStream());
						final String recvData = dis.readUTF();
						System.out.println("cliendt读取到数据："+recvData);
						new Thread(){
							public void run(){
								call.onRecvUTFNoBack(recvData);
							}
						}.start();
					}
					
				} catch (IOException e) {
					e.printStackTrace();
					Log.d("TcpSocketTwo", "readUTF IOException##########################################3");
					new Thread(){
						public void run(){
							if(mTcpStateListener!=null){
								mTcpStateListener.onDisconnect();  //回调上层连接状态
							}
						}
					}.start();
				}
			}
		}.start();
	}
	
	
	public void closeSocket(){
		if(tcpSocket != null){
			try {
				tcpSocket.shutdownInput();
				tcpSocket.shutdownOutput();
				tcpSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	
	public void setTcpStateListener(TcpStateListener tcpStateListener){
		mTcpStateListener = tcpStateListener;
	}
}
